package com.bone.eventsweb.controller;
import com.bone.eventsweb.utils.UploadUtil;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@RestController
public class ImageUploadController {

    @PostMapping("upload")
    public String upload(MultipartFile file) {
        //file校验
        if (file.isEmpty()){
            return "图片上传失败";
        }
        //file 文件重命名    a:1.png   b:  1.png
        String originalFilename = file.getOriginalFilename();  //originalFilename============16256251975051038.png

        String ext = originalFilename.split("\\.")[1];  // 1.png    拿到后缀名  png

        String uuid = UUID.randomUUID().toString().replace("-","");//0da7f3c93a834ea18638aa3723514915 以uuid生成文件名
        //新文件名
        String fileName = uuid+"." + ext;  //fileNamedc75cd16f556468fbe1af5313f6c3684png
        System.out.println("fileName"+fileName);
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());   //E:\Desktop\GW\宣传系统后台\target\classes
        //将图片最终存放的路径
        String pre = applicationHome.getDir().getParentFile().getParentFile().getAbsoluteFile()   //将其拼接成pre   E:\Desktop\GW\宣传系统后台\src\main\resources\images\
                + "\\src\\main\\resources\\static\\images\\";
        String path = pre +fileName;  //具体路径    E:\Desktop\GW\宣传系统后台\src\main\resources\images\0bc8d08d44be436b933cb137ff4f0a2e.png
        try {
            file.transferTo(new File(path));//将文件创建到这个目录下
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return path; //返回路径
    }
    @PostMapping("/ossUploadImage")
    public String ossUploadImage(MultipartFile file) throws IOException{
        return UploadUtil.uploadImage(file);
    }
}
